import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author nhsoft.lul
 */
public class Application {

    static String URL = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&serverTimezone=UTC";
    static String USER = "root";
    static String PASSWORD = "123456";

    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USER, PASSWORD);

            String sql = "drop table if exists student";
            statement = conn.prepareStatement(sql);
            statement.execute();

            sql = "create table student (id int primary key,name varchar(20))";
            statement = conn.prepareStatement(sql);
            statement.execute();

            sql = "insert into student(id,name) values(1, 'lul'),(2, 'lul2')";
            statement = conn.prepareStatement(sql);
            statement.execute();

            sql = "update student set name = ? where id= ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, "lul2");
            statement.setInt(2, 1);
            statement.executeUpdate();

            sql = "select * from student";
            statement = conn.prepareStatement(sql);
            resultSet = statement.executeQuery();
            List<Student> students = new ArrayList<>();
            while (resultSet.next()) {
                Student student = new Student(resultSet.getInt(1), resultSet.getString(2));
                students.add(student);
            }
            System.out.println("students=" + students);

            sql = "delete from student where id = ?";
            statement = conn.prepareStatement(sql);
            statement.setInt(1, 1);
            statement.execute();


            conn.close();
            statement.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
